<template>

    <div>
        <el-button type="primary" @click="handleAdd">添加用户</el-button>
        <el-button type="success" @click="handleImport">excel导入用户</el-button>
        <el-button type="success" @click="handleCsv">csv导入用户</el-button>
        <el-button @click="handleExport">导出用户</el-button>
    </div>

    <el-table :data="tableData" row-key="id">
        <el-table-column prop="roleName" label="角色名称">
            <template #default="scope">
                <div>{{ scope.row.role.roleName }}</div>
            </template>
        </el-table-column>
        <el-table-column prop="username" label="用户名"></el-table-column>


        <el-table-column label="操作">
            <template #default="scope">
                <el-button round type="primary" :disabled="scope.row.isDefault === 1"
                    @click="handleUpdate(scope.row)">更新</el-button>
                <el-popconfirm title="您确定要删除么?" confirm-button-text="确认" cancel-button-text="取消"
                    @confirm="handleDelete(scope.row)">
                    <template #reference>
                        <el-button round type="danger" :disabled="scope.row.isDefault === 1">删除</el-button>
                    </template>
                </el-popconfirm>

            </template>
        </el-table-column>
    </el-table>

    <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="pageSizes"
        layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
        @current-change="handleCurrentChange" />

    <el-dialog v-model="dialogVisible" title="添加用户">
        <el-form ref="addFormRef" :model="addForm" :rules="rules" class="demo-ruleForm" status-icon>
            <el-form-item label="用户名" prop="username">
                <el-input v-model="addForm.username" />
            </el-form-item>
            <el-form-item label="密码" prop="password">
                <el-input v-model="addForm.password" type="password" />
            </el-form-item>

            <el-form-item label="角色" prop="roleId">
                <el-select v-model="addForm.roleId" class="m-2" placeholder="请选择角色" size="large">
                    <el-option v-for="item in roleList" :key="item.id" :label="item.roleName" :value="item.id" />
                </el-select>
            </el-form-item>

            <el-form-item label="邮箱" prop="email">
                <el-input v-model="addForm.email" />
            </el-form-item>
            <el-form-item label="手机号" prop="tel">
                <el-input v-model="addForm.tel" />
            </el-form-item>

            <div class="dialog-footer">
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="handleAddConfirm()">
                    确定
                </el-button>
            </div>
        </el-form>
    </el-dialog>

    <el-dialog v-model="dialogUpdateVisible" title="更新用户">
        <el-form ref="updateFormRef" :model="updateForm" :rules="rules" class="demo-ruleForm" status-icon>
            <el-form-item label="角色" prop="roleId">
                <el-select v-model="updateForm.roleId" class="m-2" placeholder="请选择角色" size="large">
                    <el-option v-for="item in roleList" :key="item.id" :label="item.roleName" :value="item.id" />
                </el-select>
            </el-form-item>

            <div class="dialog-footer">
                <el-button @click="dialogUpdateVisible = false">取消</el-button>
                <el-button type="primary" @click="handleUpdateConfirm()">
                    确定
                </el-button>
            </div>
        </el-form>
    </el-dialog>

    <el-dialog v-model="dialogUploadVisible" title="导入用户">
        <el-link href="template/userTemplate.xlsx" type="success">请按模板导入数据，若没有模板，请点击此处下载</el-link>
        <el-upload :limit="1" :accept="'.xlsx,.xls'" class="upload-demo" drag action="/adminapi/upload/import"
            :data="data" :on-success="handleSuccess">
            <el-icon class="el-icon--upload"><upload-filled /></el-icon>
            <div class="el-upload__text">
                将文件拖到此处或<em>点击上传</em>,仅支持xlsx或xls文件格式
            </div>
        </el-upload>
    </el-dialog>

    <el-dialog v-model="dialogCsvVisible" title="导入用户">
        <el-upload :limit="1" :accept="'.csv'" class="upload-demo" drag action="/adminapi/upload/csv" :data="data"
            :on-success="handleCsvSuccess">
            <el-icon class="el-icon--upload"><upload-filled /></el-icon>
            <div class="el-upload__text">
                将文件拖到此处或<em>点击上传</em>,仅支持csv文件格式
            </div>
        </el-upload>
    </el-dialog>

</template>
<script setup>
import { ref, onMounted, reactive } from 'vue';
import { ElMessage } from 'element-plus'
import axios from 'axios';
import { UploadFilled } from '@element-plus/icons-vue'
const tableData = ref([])
const pageSizes = ref([20, 50, 100])
const pageSize = ref(pageSizes.value[0]);
const roleList = ref([])
const total = ref(0)
const currentPage = ref(1)
onMounted(() => {

    getList(currentPage.value, pageSize.value)
    getRoleList()
})
const getList = async (currentPage, pageSize) => {
    var res = await axios.get(`/adminapi/users?page=${currentPage}&size=${pageSize}`)
    tableData.value = res.data.list
    total.value = res.data.total
}

const getRoleList = async () => {
    var res = await axios.get("/adminapi/roles")
    console.log(res.data)
    roleList.value = res.data
}

const handleCurrentChange = () => {
    getList(currentPage.value, pageSize.value)
}

const handleSizeChange = () => {
    currentPage.value = 1;
    getList(currentPage.value, pageSize.value)
}

const dialogVisible = ref(false)

const handleAdd = () => {
    dialogVisible.value = true;
}

const addFormRef = ref();
const addForm = reactive({
    username: "",
    password: "",
    roleId: ""
})

const rules = reactive({
    username: [
        { required: true, message: '请输入用户名', trigger: 'blur' }
    ],
    password: [
        { required: true, message: '请输入密码', trigger: 'blur' }
    ],
    roleId: [
        { required: true, message: '请选择角色', trigger: 'blur' }
    ]
})

const handleAddConfirm = () => {
    addFormRef.value.validate(async (valid) => {
        if (valid) {
            var res = await axios.post(`/adminapi/users`, addForm);
            if (res.data.code === 0) {
                dialogVisible.value = false;
                ElMessage({
                    message: '添加成功',
                    type: 'success',
                })
                addForm.username = "";
                addForm.password = "";
                addForm.roleId = "";
                await getList(1, pageSize.value)
            } else {
                ElMessage.error(res.data.msg)
            }
        } else {
            console.log(valid)
        }
    })
}

const dialogUpdateVisible = ref(false)
const dialogUploadVisible = ref(false)
const dialogCsvVisible = ref(false)

const updateFormRef = ref();
const currentItem = ref({})
const updateForm = reactive({
    roleId: ""
})

const handleUpdate = (item) => {
    // 更新对话显示
    dialogUpdateVisible.value = true

    // updateForm 更新
    updateForm.roleId = item.roleId;

    // currentItem id
    currentItem.value = item;

}

const handleUpdateConfirm = async () => {
    var res = await axios.put(`/adminapi/users/${currentItem.value.id}`, updateForm)
    if (res.data.code === 0) {
        dialogUpdateVisible.value = false;
        ElMessage({
            message: '操作成功',
            type: 'success',
        })
        await getList(1, pageSize.value)
    }

}

const handleImport = async () => {
    dialogUploadVisible.value = true;
}

const handleExport = async () => {
    var response = await axios.get(`adminapi/user/exportExcel`, {
        responseType: 'blob'
    })
    const url = window.URL.createObjectURL(new Blob([response.data]));
    const link = document.createElement('a');
    link.href = url;
    link.setAttribute('download', 'exported_data.xlsx');
    document.body.appendChild(link);
    link.click();

    ElMessage.success('导出成功');
}

const data = {
    "token": localStorage.getItem("token")
}
const handleSuccess = (response, file, fileList) => {
    dialogUploadVisible.value = false;
    fileList.splice(fileList.indexOf(file), 1);
    ElMessage({
        message: '导入成功',
        type: 'success',
    })
    // response为后端返回的数据 eg:{code: 0, msg: '服务调用成功', data: '导入成功'}
    getList(1, pageSize.value)
}

const handleCsvSuccess = (response, file, fileList) => {
    dialogCsvVisible.value = false;
    fileList.splice(fileList.indexOf(file), 1);
    ElMessage({
        message: '导入成功',
        type: 'success',
    })
    // response为后端返回的数据 eg:{code: 0, msg: '服务调用成功', data: '导入成功'}
    getList(1, pageSize.value)
}

const handleCsv = () => {
    dialogCsvVisible.value = true;
}

const handleDelete = async ({ id }) => {
    var res = await axios.delete(`/adminapi/users/${id}`)
    if (res.data.code === 0) {
        ElMessage({
            message: '操作成功',
            type: 'success',
        })
        await getList(1, pageSize.value)
    } else {
        ElMessage.error(res.data.msg)
    }

}

</script>